#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2023/8/21 13:47
# @Author : 闫峰
# @File    : allegro_attribute_assignment.py
from datetime import datetime

import pymongo

from utils.mysqlUtils.mongodb_utils import MongoDBLink
import os

from common.setting import ensure_path_sep
from utils.logging_tool.log_control import LogHandler
from utils.mysqlUtils.db_pool import Database

current_path = os.path.abspath(__file__)
current_dir = os.path.dirname(current_path)
path_list = current_path.split("\\")
dis_path = "\\".join(path_list[-2:-1])
info_path = ensure_path_sep(f"\\logs\\info-{dis_path}.log")
error_path = ensure_path_sep(f"\\logs\\\error-{dis_path}.log")
warning_path = ensure_path_sep(f"\\logs\\warning-{dis_path}.log")
if os.path.exists(info_path):
    os.remove(info_path)
if os.path.exists(error_path):
    os.remove(error_path)
if os.path.exists(warning_path):
    os.remove(warning_path)
INFO = LogHandler(info_path, level='info')
ERROR = LogHandler(error_path, level='error')
WARNING = LogHandler(warning_path, level='warning')


class Allegro_attribute_assignment:
    modb = MongoDBLink(
        uri='mongodb://rwuser:G1mob8U3VQ1obsFxHClJ!@124.71.9.215:8635,110.41.3.226:8635/?authSource=admin',
        dbname='irobotbox_marketpublish', coll_name='Ap_AutoPublish_Allegro_Listing')
    znkd_db = Database(ensure_path_sep("\\config\\znkd_mysql_config.yaml"), "znkd_database_prod")

    def allegro_attribute_assignment(self):
        start_date = datetime(2023, 8, 28, 0, 0, 0)
        filter = {
            "AddTime": {
                "$gte": start_date
            }
        }
        page_no = 1
        while True:
            res = self.modb.select_skip_limit(filter, page_no, 100)
            if res:
                self.handler_data(res)
                page_no += 1
            else:
                break

    def handler_data(self, res):
        for data in res:
            self.handler_data_one(data)

    def handler_data_one(self, data):
        sku = data.get('Sku')
        OrderSourceId = data.get('OrderSourceId')
        category_id = data.get('Detail').get('Category').get('_id')
        attribute_list = ["Bulb Thread", "Main Pattern", "Theme", "Color", "Size", "Number of items in the set",
                          "brand"]
        # 通过 category_id 获得所有的 必传属性
        get_attribute = """
        SELECT `Name`, Type,AmbiguousValueId,Min,CustomValuesEnabled,AttributeId
        FROM `m_allegro_attribute` WHERE CustomerId=1 AND CategoryId=%s AND Required=1
        """
        attribute_list = self.znkd_db.fetch_all_tuple(get_attribute, (category_id,))
        # 遍历 必传属性
        for attribute in attribute_list:

            # if 属性 ==Bulb Thread and Type=dictionary
            if attribute[0].upper() == 'BULB THREAD' and attribute[1] == 'dictionary':
                self.handler_bulb_thread(category_id, attribute, data)
            # if 属性 ==Main Pattern and Type=dictionary
            elif attribute[0].upper() == 'MAIN PATTERN' and attribute[1] == 'dictionary':
                self.handler_main_pattern(category_id, attribute, data)
            # if 属性 ==Theme and Type=dictionary
            elif attribute[0].upper() == 'THEME' and attribute[1] == 'dictionary':
                self.handler_theme(category_id, attribute, data)
            # if 属性 ==Color and Type=dictionary
            elif attribute[0].upper() == 'COLOR' and attribute[1] == 'dictionary':
                self.handler_color(category_id, attribute, sku, data)
            # if 属性 ==Size and Type=dictionary
            elif attribute[0].upper() == 'SIZE' and attribute[1] == 'dictionary':
                self.handler_size(category_id, attribute, sku, data)
            # if 属性 ==Number of items in the set and Type=integer
            elif attribute[0].upper() == 'NUMBER OF ITEMS IN THE SET' and attribute[1] == 'integer':
                self.handler_number_of_items_in_the_set(category_id, attribute, data)
            # if 属性 ==brand and Type=dictionary
            elif attribute[0].upper() == 'BRAND' and attribute[1] == 'dictionary':
                self.handler_brand(category_id, attribute, data)
            # if 属性 Type=string
            elif attribute[1] == 'string':
                ERROR.logger.info(f"必填属性 String")
            # if 属性 Type=dictionary
            elif attribute[1] == 'dictionary':
                self.handler_dictionary(category_id, attribute, data)
            else:
                print(f"其他,属性名：{attribute[0]}")
                continue

    def handler_bulb_thread(self, category_id, attribute, data):
        AttributeId = attribute[5]
        # 通过 AttributeId， AttributeId 得到属性值列表
        get_attribute_value_list = """
        SELECT ValueId,`Value` FROM m_allegro_attribute_value 
        WHERE CustomerId=1 AND CategoryId=%s AND  AttributeId=%s and value = 'none'
        """
        attribute_value_list = self.znkd_db.fetch_all_tuple(get_attribute_value_list, (category_id, AttributeId))
        # 属性值none 存在
        if attribute_value_list:
            pass
            # INFO.logger.info(f"BULB THREAD 场景1 "
            #                  f"sku={data.get('Sku')},"
            #                  f"OrderSourceId={data.get('OrderSourceId')}"
            #                  f"category_id= {category_id} "
            #                  f"AttributeId={attribute[5]}")
        # 属性值none 不存在
        else:
            # CustomValuesEnabled
            if attribute[4] == 1:
                INFO.logger.info(f"BULB THREAD 场景3 "
                                 f"sku={data.get('Sku')},"
                                 f"OrderSourceId={data.get('OrderSourceId')}"
                                 f"category_id= {category_id} "
                                 f"AttributeId={attribute[5]}")
            else:
                INFO.logger.info(f"BULB THREAD 场景2 "
                                 f"sku={data.get('Sku')},"
                                 f"OrderSourceId={data.get('OrderSourceId')}"
                                 f"category_id= {category_id} "
                                 f"AttributeId={attribute[5]}")

    def handler_main_pattern(self, category_id, attribute, data):
        AttributeId = attribute[5]
        # 通过 AttributeId， AttributeId 得到属性值列表
        get_attribute_value_list = """
        SELECT ValueId,`Value` FROM m_allegro_attribute_value 
        WHERE CustomerId=1 AND CategoryId=%s AND  AttributeId=%s and (value = 'classic' or value='plain')
        """
        attribute_value_list = self.znkd_db.fetch_all_tuple(get_attribute_value_list, (category_id, AttributeId))
        # 属性值classic/plain 存在
        if attribute_value_list:
            pass
            # INFO.logger.info(f"MAIN PATTERN 场景1 "
            #                  f"sku={data.get('Sku')},"
            #                  f"OrderSourceId={data.get('OrderSourceId')}"
            #                  f"category_id= {category_id} "
            #                  f"AttributeId={attribute[5]}")
        # 属性值classic/plain 不存在
        else:
            # CustomValuesEnabled
            if attribute[4] == 1:
                INFO.logger.info(f"MAIN PATTERN 场景3 "
                                 f"sku={data.get('Sku')},"
                                 f"OrderSourceId={data.get('OrderSourceId')}"
                                 f"category_id= {category_id} "
                                 f"AttributeId={attribute[5]}")
            else:
                INFO.logger.info(f"MAIN PATTERN 场景2 "
                                 f"sku={data.get('Sku')},"
                                 f"OrderSourceId={data.get('OrderSourceId')}"
                                 f"category_id= {category_id} "
                                 f"AttributeId={attribute[5]}")

    def handler_theme(self, category_id, attribute, data):
        AttributeId = attribute[5]
        # 通过 AttributeId， AttributeId 得到属性值列表
        get_attribute_value_list = """
        SELECT ValueId,`Value` FROM m_allegro_attribute_value 
        WHERE CustomerId=1 AND CategoryId=%s AND  AttributeId=%s and value = 'none'
        """
        attribute_value_list = self.znkd_db.fetch_all_tuple(get_attribute_value_list, (category_id, AttributeId))
        # 属性值none 存在
        if attribute_value_list:
            pass
            # INFO.logger.info(f"THEME 场景1 "
            #                  f"sku={data.get('Sku')},"
            #                  f"OrderSourceId={data.get('OrderSourceId')}"
            #                  f"category_id= {category_id} "
            #                  f"AttributeId={attribute[5]}")
        # 属性值none 不存在
        else:
            # CustomValuesEnabled
            if attribute[4] == 1:
                INFO.logger.info(f"THEME 场景3 "
                                 f"sku={data.get('Sku')},"
                                 f"OrderSourceId={data.get('OrderSourceId')}"
                                 f"category_id= {category_id} "
                                 f"AttributeId={attribute[5]}")
            else:
                pass
                # INFO.logger.info(f"THEME 场景2 "
                #                  f"sku={data.get('Sku')},"
                #                  f"OrderSourceId={data.get('OrderSourceId')}"
                #                  f"category_id= {category_id} "
                #                  f"AttributeId={attribute[5]}")

    def handler_color(self, category_id, attribute, sku, data):
        AttributeId = attribute[5]
        get_attribute_value = """
        SELECT AttributeName,AttributeValue
        FROM p_market_product_variant WHERE CustomerId=1 AND MarketId=67 AND Sku=%s
        """
        get_attribute_value = self.znkd_db.fetch_all(get_attribute_value, (sku,))
        attribute_value_dict = {}
        if get_attribute_value:
            for j in get_attribute_value:
                attribute_value_dict[j.get('AttributeName').lower()] = j.get('AttributeValue').strip().lower()

        # 判断color的值 是否匹配到属性的下拉值列表
        color = None
        if attribute_value_dict['color']:
            color = attribute_value_dict['color']
        get_attribute_value_list = """
        SELECT `Value` FROM m_allegro_attribute_value 
        WHERE CustomerId=1 AND CategoryId=%s AND  AttributeId=%s and value like %s
        """
        color_like = f'%{color}%'
        attribute_value_color = self.znkd_db.fetch_all_tuple(get_attribute_value_list,
                                                             (category_id, AttributeId, color_like))
        if attribute_value_color:
            pass
            # ERROR.logger.error(f"color 场景1 "
            #                    f"sku={data.get('Sku')},"
            #                    f"OrderSourceId={data.get('OrderSourceId')}"
            #                    f"category_id= {category_id} "
            #                    f"AttributeId={attribute[5]}")
        else:
            multicolor = f"%multicolor%"
            attribute_value_multicolor = self.znkd_db.fetch_all_tuple(get_attribute_value_list,
                                                                      (category_id, AttributeId, multicolor))
            if attribute_value_multicolor:
                pass
                # ERROR.logger.error(f"color 场景2 "
                #                    f"sku={data.get('Sku')},"
                #                    f"OrderSourceId={data.get('OrderSourceId')}"
                #                    f"category_id= {category_id} "
                #                    f"AttributeId={attribute[5]}")
            else:
                different_colors = f"%different colors%"
                attribute_value_different_colors = self.znkd_db.fetch_all_tuple(get_attribute_value_list,
                                                                                (category_id, AttributeId,
                                                                                 different_colors))
                if attribute_value_different_colors:
                    pass
                    # ERROR.logger.error(f"color 场景3 "
                    #                    f"sku={data.get('Sku')},"
                    #                    f"OrderSourceId={data.get('OrderSourceId')}"
                    #                    f"category_id= {category_id} "
                    #                    f"AttributeId={attribute[5]}")
                else:
                    # CustomValuesEnabled
                    if attribute[4] == 1:
                        INFO.logger.info(f"THEME 场景4 "
                                         f"sku={data.get('Sku')},"
                                         f"OrderSourceId={data.get('OrderSourceId')}"
                                         f"category_id= {category_id} "
                                         f"AttributeId={attribute[5]}")
                    else:
                        pass
                        # INFO.logger.info(f"THEME 场景5 "
                        #                  f"sku={data.get('Sku')},"
                        #                  f"OrderSourceId={data.get('OrderSourceId')}"
                        #                  f"category_id= {category_id} "
                        #                  f"AttributeId={attribute[5]}")

    def handler_size(self, category_id, attribute, sku, data):
        AttributeId = attribute[5]
        get_attribute_value = """
        SELECT AttributeName,AttributeValue
        FROM p_market_product_variant WHERE CustomerId=1 AND MarketId=67 AND Sku=%s
        """
        get_attribute_value = self.znkd_db.fetch_all(get_attribute_value, (sku,))
        attribute_value_dict = {}
        if get_attribute_value:
            for j in get_attribute_value:
                attribute_value_dict[j.get('AttributeName').lower()] = j.get('AttributeValue').strip().lower()

        # 判断size的值 是否匹配到属性的下拉值列表
        size = None
        if attribute_value_dict['size']:
            size = attribute_value_dict['size']
        get_attribute_value_list = """
        SELECT `Value` FROM m_allegro_attribute_value 
        WHERE CustomerId=1 AND CategoryId=%s AND  AttributeId=%s and value like %s
        """
        attribute_value_size = self.znkd_db.fetch_all_tuple(get_attribute_value_list,
                                                            (category_id, AttributeId, size))
        if attribute_value_size:
            pass
            # ERROR.logger.error(f"size 场景1 "
            #                    f"sku={data.get('Sku')},"
            #                    f"OrderSourceId={data.get('OrderSourceId')}"
            #                    f"category_id= {category_id} "
            #                    f"AttributeId={attribute[5]}")
        else:
            nonstandard = f"%nonstandard%"
            attribute_value_nonstandard = self.znkd_db.fetch_all_tuple(get_attribute_value_list,
                                                                       (category_id, AttributeId, nonstandard))
            if attribute_value_nonstandard:
                pass
                # ERROR.logger.error(f"size 场景2 "
                #                    f"sku={data.get('Sku')},"
                #                    f"OrderSourceId={data.get('OrderSourceId')}"
                #                    f"category_id= {category_id} "
                #                    f"AttributeId={attribute[5]}")
            else:
                # CustomValuesEnabled
                if attribute[4] == 1:
                    INFO.logger.info(f"size 场景3 "
                                     f"sku={data.get('Sku')},"
                                     f"OrderSourceId={data.get('OrderSourceId')}"
                                     f"category_id= {category_id} "
                                     f"AttributeId={attribute[5]}")
                else:
                    pass
                    # INFO.logger.info(f"size 场景4 "
                    #                  f"sku={data.get('Sku')},"
                    #                  f"OrderSourceId={data.get('OrderSourceId')}"
                    #                  f"category_id= {category_id} "
                    #                  f"AttributeId={attribute[5]}")

    @staticmethod
    def handler_number_of_items_in_the_set(category_id, attribute, data):
        min_value = int(attribute[3])
        if min_value == 0:
            pass
            # INFO.logger.info(f"number_of_items_in_the_set 场景1 "
            #                  f"sku={data.get('Sku')},"
            #                  f"OrderSourceId={data.get('OrderSourceId')}"
            #                  f"category_id= {category_id} "
            #                  f"AttributeId={attribute[5]}")

        else:
            ERROR.logger.info(f"number_of_items_in_the_set 场景2 "
                              f"sku={data.get('Sku')},"
                              f"OrderSourceId={data.get('OrderSourceId')}"
                              f"category_id= {category_id} "
                              f"AttributeId={attribute[5]}")

    def handler_dictionary(self, category_id, attribute, data):
        # 判断 AmbiguousValueId 是否有值
        if attribute[2]:
            # CustomValuesEnabled
            if attribute[4] == 1:
                INFO.logger.info(f"dictionary 场景1 date:{data}")
            else:
                pass
                # INFO.logger.info(f"dictionary 场景2 date:{data}")
        else:
            AttributeId = attribute[5]
            # 通过 AttributeId， AttributeId 得到属性值列表
            get_attribute_value_list = """
            SELECT `Value` FROM m_allegro_attribute_value 
            WHERE CustomerId=1 AND CategoryId=%s AND  AttributeId=%s 
            """
            attribute_value_list = self.znkd_db.fetch_all_tuple(get_attribute_value_list, (category_id, AttributeId))
            attribute_value_list = list(map(lambda x: x[0], attribute_value_list))
            if "inna" in attribute_value_list:
                INFO.logger.info(f"data={data},"
                                 f"category_id= {category_id} "
                                 f"AttributeId={AttributeId}"
                                 f"场景 inna存在")

    def handler_brand(self, category_id, attribute, data):
        AttributeId = attribute[5]
        get_attribute_value_list = """
        SELECT ValueId  FROM m_allegro_attribute_value 
        WHERE CustomerId=1 AND CategoryId=%s AND  AttributeId=%s and BINARY value ='no brand'
        """

        attribute_value_no_brand = self.znkd_db.fetch_all_tuple(get_attribute_value_list,
                                                                (category_id, AttributeId))
        if attribute_value_no_brand:
            pass
            # INFO.logger.info(f"brand 场景1 下拉值no_brand 查询到了"
            #                  f"sku={data.get('Sku')},"
            #                  f"OrderSourceId={data.get('OrderSourceId')}"
            #                  f"category_id= {category_id} "
            #                  f"AttributeId={attribute[5]}")
        else:
            get_attribute_value_list = """
            SELECT ValueId  FROM m_allegro_attribute_value 
            WHERE CustomerId=1 AND CategoryId=%s AND  AttributeId=%s and BINARY value ='No brand'
            """

            attribute_value_No_brand = self.znkd_db.fetch_all_tuple(get_attribute_value_list,
                                                                    (category_id, AttributeId))
            if attribute_value_No_brand:
                INFO.logger.info(f"brand 场景2 下拉值 No_brand 查询到了 "
                                 f"sku={data.get('Sku')},"
                                 f"OrderSourceId={data.get('OrderSourceId')}"
                                 f"category_id= {category_id} "
                                 f"AttributeId={attribute[5]}")
            else:
                # CustomValuesEnabled
                if attribute[4] == 1:
                    INFO.logger.info(f"brand 场景3 "
                                     f"sku={data.get('Sku')},"
                                     f"OrderSourceId={data.get('OrderSourceId')}"
                                     f"category_id= {category_id} "
                                     f"AttributeId={attribute[5]}")
                else:
                    pass
                    # INFO.logger.info(f"brand 场景4 "
                    #                  f"sku={data.get('Sku')},"
                    #                  f"OrderSourceId={data.get('OrderSourceId')}"
                    #                  f"category_id= {category_id} "
                    #                  f"AttributeId={attribute[5]}")



if __name__ == '__main__':
    Allegro_attribute_assignment().allegro_attribute_assignment()
